package org.su.webadapter.bind;


import org.su.generalmvc.IEditor;
import org.su.generalmvc.core.InitialContext;
import org.su.generalmvc.entity.PojoCache;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class BeanEditor extends AbstractBeanEditor implements IEditor {

	@Override
	public Object getParamValue(String paramName, Class<?> paramType, int paramIndex, Method writer,
			ServletRequest request, ServletResponse response) {
		if (!isContinueParam(paramName, request)) {
			return null;
		}
		try {
			PojoCache pc = InitialContext.getInstance().getContext().getPojoContext().get(paramType.getName());
			if(pc == null){
				return null;
			}
			Object obj = null;
			String prifix = paramName + ".";
			List<String> names = pc.getMethodNames();
			Object value = null;
			String name = null;
			String paramValue = null;
			for(int i=0;i<names.size();i++){
				    name = prifix + names.get(i);
					value = pc.getEditors().get(i).getParamValue(name,	pc.getReadMethods().get(i).getReturnType(), 0, pc.getMethods().get(i),
							request, response);
				     paramValue = request.getParameter(name);
					if(value!=null){
						/**
						 * 当value为number类型时,默认值都为0,所以即使form中没有这个参数,默认值也是0,所以要排除这种情况。
                         */
						if( (paramValue == null || paramValue.length() == 0) && value.toString().equals("0") ){
							continue;
						}
                        if(obj == null){
                            obj = paramType.newInstance();
                        }
						pc.getMethods().get(i).invoke(obj, value);
					}

			}

			paramType = null;
			name = null;
			paramValue = null;
			value = null;
			names = null;
			prifix = null;

			return obj;
			
		} catch (Exception e) {
			throw new ParamBindException(e, "param name is :" + paramName);
		}
	}





}
